package com.msx.trade.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.security.MD5Encoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class MD5Sign {

    public static void main(String[] args) {

      /*  Map<String, String>map=new HashMap<String,String>();
        map.put("name", "大宝");
        map.put("cardId", "123");
        *//*map.put("name", "harry");
        map.put("b", "harry");
        map.put("level", "top");
        map.put("g", "");
        map.put("m", "lal");
        map.put("alary", 1000);*//*
        String appSercret="aea43111aa87807fb79939b28256b929";
        String sign = sign(map,appSercret);
        System.out.println("签名为================="+sign);*/
        //System.out.println(md5Encode("123456"));
        String str = Base64.getEncoder().encodeToString("15921484451".getBytes());
        System.out.println(str);

    }

    /**
     *
     * @param text
     *            明文
     * @return 32位密文
     */
    public static String md5Encode(String text) {
        String str=null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            str = MD5Encoder.encode(md.digest(text.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return str;
    }


    /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, String> sortMap = new TreeMap<String, String>();
        Iterator<String> iter = map.keySet().iterator();
        while(iter.hasNext()){
            String key=iter.next();
            String value = map.get(key);
            if("merId".equals(key)){
                continue;
            }
            if("sign".equals(key)){
                continue;
            }
            if(value==null || value.equals("")){
                continue;
            }
            sortMap.put(key,value);
        }
        return sortMap;
    }


    /**
     * 签名
     */
    public static String sign(Map<String,String> map,String appSercret){
        System.out.println("排序前："+map);
        map=sortMapByKey(map);
        System.out.println("排序后"+map);

        List<Object> list=new ArrayList<Object>();
        String str="";
        Iterator<String> iter = map.keySet().iterator();
        while(iter.hasNext()){
            String key=iter.next();
            Object value = map.get(key);
            list.add(key+"="+value);
        }
        str = StringUtils.join(list,"&")+"&"+appSercret;
        System.out.println(str);
        return md5Encode(str);
    }

}
